package com.ywdnf.gomoku.configuration;

import com.ywdnf.gomoku.model.auth.MyPrincipal;
import com.ywdnf.gomoku.util.CommonUtil;
import com.ywdnf.gomoku.util.Const;
import java.security.Principal;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.server.support.DefaultHandshakeHandler;

/**
 * websocket 配置
 *
 * @author lss
 * @date 2019-01-19, Sat
 */
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

  @Bean
  MyHandShakeInterceptor myHandShakeInterceptor() {
    return new MyHandShakeInterceptor();
  }

  @Override
  public void registerStompEndpoints(StompEndpointRegistry registry) {
    registry
        .addEndpoint("/gmkServer")
        .setAllowedOrigins("*")
        .setHandshakeHandler(new MyHandShakeInterceptor())
        .withSockJS();
  }

  @Override
  public void configureMessageBroker(MessageBrokerRegistry registry) {

    registry.enableSimpleBroker("/topic", "/queue");
    registry.setApplicationDestinationPrefixes("/app");

  }
}

class MyHandShakeInterceptor extends DefaultHandshakeHandler {

  /**
   * PRINCIPAL_MAP
   */
  private static final Map<String, MyPrincipal> PRINCIPAL_MAP = new ConcurrentHashMap<>();

  @Override
  protected Principal determineUser(ServerHttpRequest request, WebSocketHandler wsHandler,
      Map<String, Object> attributes) {
    String url = request.getURI().toString();
    Map<String, String> params = CommonUtil.getQueryParams(url);
    String userId = params.get(Const.PARAM_USER_ID_IN_URL);
    MyPrincipal myPrincipal = PRINCIPAL_MAP.get(userId);
    if (myPrincipal == null) {
      myPrincipal = new MyPrincipal(userId);
      PRINCIPAL_MAP.put(userId, myPrincipal);
    }
    return myPrincipal;

  }

  /**
   * 获取某个用户的principal
   *
   * @param key 用户ufid
   * @return principal
   */
  public static MyPrincipal getPrincipalByKey(String key) {
    return PRINCIPAL_MAP.get(key);
  }

}